import React, { useState, useEffect, useCallback } from 'react';
import {
  Layout,
  Tooltip,
  Button as AntButton,
  Modal,
  Input,
  Form,
  Table,
  Space,
  Popconfirm,
  Select,
  InputNumber,
  Tabs,
  App
} from 'antd';
import type { TableProps, TablePaginationConfig } from 'antd';
import {
  ArrowLeftOutlined,
  SearchOutlined,
  PlusOutlined,
  FilterOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { Button } from '../../components/common/Button';
import { tablesService, areasService } from '../../services';
import type { Table as TableType, Area } from '../../services';
import MerchantSelector from '../../components/common/MerchantSelector';
import './TablesPage.css';

const { Header, Content } = Layout;
const { Option } = Select;
const { TabPane } = Tabs;

// 餐桌状态类型
type TableStatus = 'free' | 'occupied' | 'reserved' | 'cleaning';

// 获取状态显示文本
const getStatusText = (status: string) => {
  switch (status?.toLowerCase()) {
    case 'free':
      return '空闲';
    case 'occupied':
      return '使用中';
    case 'reserved':
      return '已预订';
    case 'cleaning':
      return '清理中';
    default:
      return status;
  }
};

export const TablesPage: React.FC = () => {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState<string>('tables');
  const { message } = App.useApp();

  // 餐桌相关状态
  const [loading, setLoading] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [tables, setTables] = useState<TableType[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [modalVisible, setModalVisible] = useState(false);
  const [editingTable, setEditingTable] = useState<TableType | null>(null);
  const [form] = Form.useForm();

  // 区域相关状态
  const [areaLoading, setAreaLoading] = useState(false);
  const [areaSearchText, setAreaSearchText] = useState('');
  const [areas, setAreas] = useState<Area[]>([]);
  const [areaPagination, setAreaPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [areaModalVisible, setAreaModalVisible] = useState(false);
  const [editingArea, setEditingArea] = useState<Area | null>(null);
  const [areaForm] = Form.useForm();

  // 加载数据
  useEffect(() => {
    fetchTables();
    fetchAreas(); // 提前加载区域数据
  }, []);

  // 获取餐桌数据
  const fetchTables = useCallback(async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await tablesService.getTableList({
        page,
        pageSize
      });
      if (response.code === 0 && response.data) {
        setTables(response.data.list || []);
        setPagination({
          ...pagination,
          current: page,
          total: response.data.total || 0,
        });
      } else {
        message.error(response.message || '获取餐桌失败');
      }
    } catch (error) {
      console.error('获取餐桌失败:', error);
      message.error('获取餐桌失败');
    } finally {
      setLoading(false);
    }
  }, [pagination, message]);

  // 获取区域数据
  const fetchAreas = useCallback(async (page = 1, pageSize = 10) => {
    setAreaLoading(true);
    try {
      const response = await areasService.getAreaList({
        page,
        pageSize
      });
      if (response.code === 0 && response.data) {
        setAreas(response.data.list || []);
        setAreaPagination({
          ...areaPagination,
          current: page,
          total: response.data.pagination?.total || 0,
        });
      } else {
        message.error(response.message || '获取区域失败');
      }
    } catch (error) {
      console.error('获取区域失败:', error);
      message.error('获取区域失败');
    } finally {
      setAreaLoading(false);
    }
  }, [areaPagination, message]);

  // 搜索餐桌
  const handleSearch = (value: string) => {
    setSearchText(value);
    fetchTables(1, pagination.pageSize);
  };

  // 搜索区域
  const handleAreaSearch = (value: string) => {
    setAreaSearchText(value);
    fetchAreas(1, areaPagination.pageSize);
  };

  // 返回上一页
  const handleBack = () => {
    navigate(-1);
  };

  // 餐桌分页变化
  const handleTableChange = (newPagination: TablePaginationConfig) => {
    fetchTables(newPagination.current || 1, newPagination.pageSize || 10);
  };

  // 区域分页变化
  const handleAreaTableChange = (newPagination: TablePaginationConfig) => {
    fetchAreas(newPagination.current || 1, newPagination.pageSize || 10);
  };

  // 打开餐桌编辑模态框
  const openModal = (record?: TableType) => {
    setEditingTable(record || null);
    form.resetFields();
    if (record) {
      // 从区域名称查找区域ID
      form.setFieldsValue({
        tableNo: record.name,
        seats: record.seats,
        areaId: record.areaId || undefined,
      });
    } else {
      // 新增时设置默认状态
      form.setFieldsValue({
        status: 'free'
      });
    }
    setModalVisible(true);
  };

  // 打开区域编辑模态框
  const openAreaModal = (record?: Area) => {
    setEditingArea(record || null);
    areaForm.resetFields();
    if (record) {
      areaForm.setFieldsValue({
        name: record.name,
        status: record.status || 'active'
      });
    } else {
      // 新增时设置默认状态
      areaForm.setFieldsValue({
        status: 'active'
      });
    }
    setAreaModalVisible(true);
  };

  // 提交餐桌表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      const params = {
        tableNo: values.tableNo,
        seats: values.seats,
        areaId: values.areaId || 0,
      };

      if (editingTable) {
        // 编辑餐桌
        const response = await tablesService.updateTable(editingTable.id, params);
        if (response.code === 0) {
          message.success('更新餐桌成功');
          fetchTables(pagination.current, pagination.pageSize);
          setModalVisible(false);
        } else {
          message.error(response.message || '更新餐桌失败');
        }
      } else {
        // 添加餐桌
        const response = await tablesService.createTable(params);
        if (response.code === 0) {
          message.success('添加餐桌成功');
          fetchTables(pagination.current, pagination.pageSize);
          setModalVisible(false);
        } else {
          message.error(response.message || '添加餐桌失败');
        }
      }
    } catch (error) {
      console.error('提交餐桌表单失败:', error);
    }
  };

  // 提交区域表单
  const handleAreaSubmit = async () => {
    try {
      const values = await areaForm.validateFields();
      const params = {
        name: values.name,
        status: values.status
      };

      if (editingArea) {
        // 编辑区域
        const response = await areasService.updateArea(editingArea.id, params);
        if (response.code === 0) {
          message.success('更新区域成功');
          fetchAreas(areaPagination.current, areaPagination.pageSize);
          setAreaModalVisible(false);
        } else {
          message.error(response.message || '更新区域失败');
        }
      } else {
        // 添加区域
        const response = await areasService.createArea(params);
        if (response.code === 0) {
          message.success('添加区域成功');
          fetchAreas(areaPagination.current, areaPagination.pageSize);
          setAreaModalVisible(false);
        } else {
          message.error(response.message || '添加区域失败');
        }
      }
    } catch (error) {
      console.error('提交区域表单失败:', error);
    }
  };

  // 删除餐桌
  const handleDelete = async (id: number) => {
    try {
      const response = await tablesService.deleteTable(id);
      if (response.code === 0) {
        message.success('删除餐桌成功');
        fetchTables(pagination.current, pagination.pageSize);
      } else {
        message.error(response.message || '删除餐桌失败');
      }
    } catch (error) {
      console.error('删除餐桌失败:', error);
      message.error('删除餐桌失败');
    }
  };

  // 删除区域
  const handleAreaDelete = async (id: number) => {
    try {
      const response = await areasService.deleteArea(id);
      if (response.code === 0) {
        message.success('删除区域成功');
        fetchAreas(areaPagination.current, areaPagination.pageSize);
      } else {
        message.error(response.message || '删除区域失败');
      }
    } catch (error) {
      console.error('删除区域失败:', error);
      message.error('删除区域失败');
    }
  };

  // 表格列配置
  const tableColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '餐桌',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '区域',
      dataIndex: 'area',
      key: 'area',
      width: 150,
      render: (area: string) => area || '未分区'
    },
    {
      title: '座位数',
      dataIndex: 'seats',
      key: 'seats',
      width: 100,
    },
    // {
    //   title: '状态',
    //   dataIndex: 'processingTrade',
    //   key: 'status',
    //   width: 120,
    //   render: (processingTrade: boolean) => {
    //     const status = processingTrade ? 'occupied' : 'free';
    //     return (
    //       <div className={`status-tag status-tag-${status}`}>
    //         {getStatusText(status)}
    //       </div>
    //     );
    //   }
    // },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_: unknown, record: TableType) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <AntButton
              icon={<EditOutlined />}
              size="small"
              onClick={() => openModal(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定删除该餐桌吗？"
              onConfirm={() => handleDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <AntButton
                icon={<DeleteOutlined />}
                size="small"
                danger
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      )
    }
  ];

  // 区域表格列配置
  const areaColumns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '区域名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 200,
      render: (createdAt: string) => createdAt ? new Date(createdAt).toLocaleString() : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: unknown, record: Area) => (
        <Space size="middle">
          <Tooltip title="编辑">
            <AntButton
              icon={<EditOutlined />}
              size="small"
              onClick={() => openAreaModal(record)}
            />
          </Tooltip>
          <Tooltip title="删除">
            <Popconfirm
              title="确定删除该区域吗？"
              onConfirm={() => handleAreaDelete(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <AntButton
                icon={<DeleteOutlined />}
                size="small"
                danger
              />
            </Popconfirm>
          </Tooltip>
        </Space>
      )
    }
  ];

  const filterTableColumns = searchText ?
    tableColumns.filter(item => item.key !== 'id') :
    tableColumns;

  const filterAreaColumns = areaSearchText ?
    areaColumns.filter(item => item.key !== 'id' && item.key !== 'createdAt') :
    areaColumns;

  return (
    <Layout className="tables-layout">
      <Header className="tables-header">
        <div className="header-left">
          <AntButton className="back-button" type="text" icon={<ArrowLeftOutlined />} size="large" onClick={handleBack} />
          <h1 className="page-title">餐厅管理</h1>
        </div>
        <div className="header-right">
          <Button
            icon={<PlusOutlined />}
            variant="primary"
            onClick={() => activeTab === 'tables' ? openModal() : openAreaModal()}
          >
            {activeTab === 'tables' ? '添加餐桌' : '添加区域'}
          </Button>
        </div>
      </Header>

      <Content className="tables-content">
        <Tabs
          className="styled-tabs"
          activeKey={activeTab}
          onChange={setActiveTab}
          type="card"
        >
          <TabPane tab="餐桌管理" key="tables" style={{ padding: 16, backgroundColor: '#fff' }}>
            {/* <div className="toolbar-container">
              <div className="search-container">
                <Input 
                  prefix={<SearchOutlined />} 
                  placeholder="搜索餐桌..." 
                  allowClear
                  value={searchText}
                  onChange={e => handleSearch(e.target.value)}
                  style={{ maxWidth: 300 }}
                />
                <Tooltip title="筛选条件">
                  <AntButton icon={<FilterOutlined />} onClick={() => message.info('筛选功能开发中')}>筛选</AntButton>
                </Tooltip>
              </div>
              <span className="text-gray-500">
                共 {pagination.total} 张餐桌
              </span>
            </div> */}

            <Table
              className="styled-table"
              columns={filterTableColumns}
              dataSource={tables}
              rowKey="id"
              pagination={pagination}
              loading={loading}
              onChange={handleTableChange}
              scroll={{ x: 1000 }}
              locale={{ emptyText: '暂无数据' }}
            />
          </TabPane>

          <TabPane tab="区域管理" key="areas" style={{padding: 16,backgroundColor: '#fff'}}>
            {/* <div className="toolbar-container">
              <div className="search-container">
                <Input 
                  prefix={<SearchOutlined />} 
                  placeholder="搜索区域..." 
                  allowClear
                  value={areaSearchText}
                  onChange={e => handleAreaSearch(e.target.value)}
                  style={{ maxWidth: 300 }}
                />
              </div>
              <span className="text-gray-500">
                共 {areaPagination.total} 个区域
              </span>
            </div> */}

            <Table
              className="styled-area-table"
              columns={filterAreaColumns}
              dataSource={areas}
              rowKey="id"
              pagination={areaPagination}
              loading={areaLoading}
              onChange={handleAreaTableChange}
              scroll={{ x: 800 }}
              locale={{ emptyText: '暂无数据' }}
            />
          </TabPane>
        </Tabs>
      </Content>

      {/* 添加/编辑餐桌模态框 */}
      <Modal
        title={editingTable ? '编辑餐桌' : '添加餐桌'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSubmit}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            name="tableNo"
            label="餐桌名称"
            rules={[{ required: true, message: '请输入餐桌名称' }]}
          >
            <Input placeholder="请输入餐桌名称" />
          </Form.Item>

          <Form.Item
            name="seats"
            label="座位数"
            rules={[{ required: true, message: '请输入座位数' }]}
          >
            <InputNumber min={1} max={50} placeholder="请输入座位数" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="areaId"
            label="区域"
          >
            <Select placeholder="请选择区域">
              {areas.map(area => (
                <Option key={area.id} value={area.id}>{area.name}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加/编辑区域模态框 */}
      <Modal
        title={editingArea ? '编辑区域' : '添加区域'}
        open={areaModalVisible}
        onCancel={() => setAreaModalVisible(false)}
        onOk={handleAreaSubmit}
        okText="确定"
        cancelText="取消"
      >
        <Form
          form={areaForm}
          layout="vertical"
        >
          <Form.Item
            name="name"
            label="区域名称"
            rules={[{ required: true, message: '请输入区域名称' }]}
          >
            <Input placeholder="请输入区域名称" />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default TablesPage; 